package com.kchouse.jpush;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.annotation.TargetApi;
import android.widget.RemoteViews;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.common.API;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.common.ToastUtils;
import com.kchouse.homepage.DepositmanagementActivity;
import com.kchouse.homepage.OffermanageActivity;
import com.kchouse.homepage.WorkordermanagementActivity;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.mine.MineMessageActivity;
import com.kchouse.mine.MineprestoreActivity;
import com.kchouse.mine.OrderActivity;
import com.kchouse.union.MerchantDetailsActivity;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import cn.jpush.android.api.JPushInterface;

import static android.content.Context.NOTIFICATION_SERVICE;

public class MyReceiver extends BroadcastReceiver {

    private String typemes;//消息类型
    private Context context;
    private Intent intent = new Intent();
    private String merchantId;//商家id

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        Bundle bundle = intent.getExtras();
        Log.e("0000", "onReceive - " + intent.getAction());
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.e("0000", "[MyReceiver] 接收 Registration Id : " + regId);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.e("0000", "收到了自定义消息。消息内容是：" + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            ToastUtils.getInstanc(context).showToast("收到了自定义消息。消息内容是：" + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            //自定义消息不会展示在通知栏，完全要开发者写代码去处理
            SentNotification(context, bundle.getString(JPushInterface.EXTRA_MESSAGE));
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
//            String REGISTRATION_ID = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            String type = bundle.getString(JPushInterface.EXTRA_EXTRA);
//            String EXTRA_MESSAGE = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            JSONObject json = JSONObject.parseObject(type);
            typemes = json.getString("type");
            merchantId = json.getString("merchantId");
            switch (typemes) {
                case "LOGOUT_NOTIFY":
                    ToastUtils.getInstanc(context).showToast("您的账号已经在其他设备登录，请重新登录");
                    loginout();
                    break;

            }
            Log.e("0000", typemes);
            // 在这里可以做些统计，或者做些其他工作
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.e("0000", "用户点击打开了通知");
            // 在这里可以自己写代码去定义用户点击后的行为
            Intent intent2 = new Intent();  //自定义打开的界面
            String type = bundle.getString(JPushInterface.EXTRA_EXTRA);
            JSONObject json = JSONObject.parseObject(type);
            typemes = json.getString("type");
            merchantId = json.getString("merchantId");

            switch (typemes) {
                case "FOLLOW_NOTIFY"://关注商家活动通知 (跳转商家详情)
                    intent2.putExtra("Merchantid", merchantId);
                    intent2.setClass(context,MerchantDetailsActivity.class);
                    context.startActivity(intent2);
                    break;
                case "EARNEST_NOTIFY"://定金通知(跳转定金管理)
                    intent2.setClass(context,DepositmanagementActivity.class);
                    context.startActivity(intent2);
                    break;
                case "WORK_NOTIFY"://工单通知通知 (跳转工单详情)
                    intent2.setClass(context,WorkordermanagementActivity.class);
                    context.startActivity(intent2);
                    break;
                case "QUOTE_NOTIFY"://报价通知 (跳转报价管理)
                    intent2.setClass(context, OffermanageActivity.class);
                    context.startActivity(intent2);
                    break;
//                case "NOTICE_NOTIFY"://公告通知 (跳转首页)
//                    intent.setClass(context, MineMessageActivity.class);
//                    contextstartActivity(intent);
//                    break;
                case "PRESTORE_CONFIRM"://预存核销确认 (跳转我的预存)
                    intent2.setClass(context, MineprestoreActivity.class);
                    context.startActivity(intent2);
                    break;
                case "SUIT_CONFIRM"://套餐项目核销确认 (跳转消费与评价)
                    intent2.putExtra("ordertype","消费与评价");
                    intent2.setClass(context, OrderActivity.class);
                    context.startActivity(intent2);
                    break;

            }
        } else {
            Log.e("0000", "Unhandled intent - " + intent.getAction());
        }
    }


    /**
     * 退出登录
     */
    private void loginout() {
        String url = API.PostLogout + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
//                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    Log.e("==", json.getString("data"));
                    SharedPreferencesUtil.setParam(context, "token", "");//保存用户token
                    SharedPreferencesUtil.setParam(context, "mobile", "");//保存用户电话
                    SharedPreferencesUtil.setParam(context, "userid", "");//保存用户id
                    intent.setClass(context, LoginPhoneActivity.class);
                    context.startActivity(intent);

                    Intent mIntent = new Intent("LoginAction");
                    //发送广播
                    context.sendBroadcast(mIntent);
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
//                dismissdialog();
            }
        });
    }


    /**
     * 发送自定义消息
     *
     * @param context
     */
    private void SentNotification(Context context, String message) {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        RemoteViews remoteViews = new RemoteViews("com.kchouse", R.layout.lay_notification_item);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService
                (NOTIFICATION_SERVICE);
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setContent(remoteViews);
//        remoteViews.setImageViewResource(R.id.iv_item, R.mipmap.ic_launcher);
//            remoteViews.setTextViewText(R.id.title, "我是标题");
        remoteViews.setTextViewText(R.id.tv_message, message);

        notificationManager.notify(10, mBuilder.build());
    }
}
